import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import glob

def publish_images(folder_path, topic):
    # 初始化ROS节点
    rospy.init_node('image_publisher')

    # 创建图像发布者
    image_publisher = rospy.Publisher(topic, Image, queue_size=10)

    # 创建CvBridge对象
    bridge = CvBridge()

    # 获取文件夹下所有图像文件的路径
    image_files = glob.glob(folder_path + '/*.png')  # 修改图像文件扩展名，根据实际情况选择

    # 设置发送频率为10Hz（每100毫秒发送一次）
    rate = rospy.Rate(10)

    for image_file in image_files:
        # 读取图像
        image = cv2.imread(image_file)

        # 将图像转换为ROS消息
        image_msg = bridge.cv2_to_imgmsg(image, encoding='bgr8')

        # 发布图像消息到指定的ROS话题
        image_publisher.publish(image_msg)

        rospy.loginfo("Image published: %s", image_file)

        # 等待100毫秒
        rate.sleep()

    rospy.loginfo("All images published to topic: %s", topic)

if __name__ == '__main__':
    # 设置文件夹路径和ROS话题
    folder_path = '/home/atakanoinu/Desktop/08/image_0'
    topic = '/camera/images'

    try:
        publish_images(folder_path, topic)
    except rospy.ROSInterruptException:
        pass